<?php

namespace app\common\model;

use app\common\validate\MemberValidate;
use think\Model;
use think\model\concern\SoftDelete;

class Member extends Model
{
    //软删除
    use SoftDelete;
    // 只读字段
    protected $readonly = ['username', 'email'];

    // 关联评论
    public function comments()
    {
        return $this->hasMany('Comment', 'member_id', 'id');
    }

    // 会员添加
    public function add($data)
    {
        $validate = new MemberValidate();
        if (!$validate->scene('add')->check($data)) {
            return $validate->getError();
        }
        $data['password'] = md5($data['password']);
        $result = $this->allowField(true)->save($data);
        if ($result) {
            return 1;
        } else {
            return '会员添加失败';
        }
    }

    // 编辑会员
    public function edit($data)
    {
        $validate = new MemberValidate();
        if (!$validate->scene('edit')->check($data)) {
            return $validate->getError();
        }
        $member_info = $this->find($data['id']);
        if (!$member_info) {
            abort('404', '该会员未找到');
        }
        // 校验原密码是否正确
        if ($member_info->password != md5($data['password'])) {
            return '原密码输入不正确';
        }
        $member_info->username = $data['username'];
        $member_info->nickname = $data['nickname'];
        $member_info->password = md5($data['new_password']);
        $member_info->email = $data['email'];
        $result = $member_info->save();
        if ($result) {
            return 1;
        } else {
            return '会员编辑失败';
        }
    }

    // 会员注册
    public function register($data)
    {
        $validate = new MemberValidate();
        if (!$validate->scene('register')->check($data)) {
            return $validate->getError();
        }
        $data['password'] = md5($data['password']);
        $result = $this->allowField(true)->save($data);
        if ($result) {
            return 1;
        } else {
            return '会员注册失败';
        }
    }

    // 会员登录
    public function login($data)
    {
        $validate = new MemberValidate();
        if (!$validate->scene('login')->check($data)) {
            return $validate->getError();
        }
        $data['password'] = md5($data['password']);
        unset($data['verify']);
        $result = $this->where($data)->find();
        if ($result) {
            $session_data = [
                'id' => $result['id'],
                'username' => $result['username'],
                'nickname' => $result['nickname'],
            ];
            // 保存session数据
            session('member', $session_data);
            return 1;
        } else {
            return '用户名或密码错误!';
        }
    }


}
